package com.rcloud.server.sealtalk.controller;


import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.ijpay.alipay.AliPayApi;
import com.rcloud.server.sealtalk.configuration.bean.AliPayBean;
import com.rcloud.server.sealtalk.enums.PayType;
import com.rcloud.server.sealtalk.exception.ServiceException;
import com.rcloud.server.sealtalk.service.PayService;
import com.rcloud.server.sealtalk.service.WxPayService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/notice/pay")
@AllArgsConstructor
public class PayNoticeController {

    private AliPayBean aliPayBean;

    private WxPayService wxPayService;

    private PayService payService;
    /**
     * 微信异步通知
     */
    @RequestMapping(value = "/wx/payNotify", method = {RequestMethod.POST, RequestMethod.GET})
    public ResponseEntity<String> payNotify(HttpServletRequest request) throws ServiceException {
        return ResponseEntity.ok(wxPayService.payNotify(request));
    }
    /**
     * 支付宝异步通知
     */
    @RequestMapping(value = "/ali/payNotify")
    public ResponseEntity<String> notifyUrl(HttpServletRequest request) {
        try {
            // 获取支付宝POST过来反馈信息
            Map<String, String> params = AliPayApi.toMap(request);
            for (Map.Entry<String, String> entry : params.entrySet()) {
                log.info(entry.getKey() + " = " + entry.getValue());
            }
            boolean verifyResult = AlipaySignature.rsaCheckV1(params, aliPayBean.getPublicKey(), "UTF-8", "RSA2");
            if (verifyResult) {
                //请在这里加上商户的业务逻辑程序代码 异步通知可能出现订单重复通知 需要做去重处理（完成）
                //支付商户支付的订单号
                String payNo = params.get("out_trade_no");
                //业务类型
                String bizType = params.get("passback_params");
                payService.paySuccess(payNo,bizType, PayType.ALIPAY.value());
                log.info("notify_url 验证成功success");
                return ResponseEntity.ok("success");
            } else {
                log.info("notify_url 验证失败");
                return ResponseEntity.ok("failure");
            }
        } catch (AlipayApiException | ServiceException e) {
            e.printStackTrace();
            return ResponseEntity.ok("failure");
        }
    }


}